import os
from django.db import models
from django.utils import timezone
import random
from django.conf import settings
from django.contrib.auth.models import User

# 默认头像路径
PORTRAIT_DEFAULT_PATH = "images/default_portrait.jpg"


def user_portrait_upload_to(instance, filename):
    """
    控制portrait的上传路径及文件名的函数，
    使用时配置FileFile类似字段upload_to参数为此函数
    参数由django 保存时自动传入。
    :param instance:  实例
    :param filename: 原始文件名
    :return:
    """
    ext = os.path.splitext(filename)[1]
    fn = "%s_%s%s" % (timezone.now().strftime("%Y%m%d%H%M%S"),
                      random.randint(100000, 999999),
                      ext)
    # 若指定的是文件名，则保存到配置的MEDIA_ROOT路径
    return "portrait/%s" % fn


class LoginUser(models.Model):
    username = models.CharField(max_length=20, unique=True)
    password = models.CharField(max_length=100)
    nickname = models.CharField(max_length=50)
    portrait = models.ImageField(upload_to=user_portrait_upload_to, default="images/default_portrait.jpg")

    def __str__(self):
        return self.username

    def get_portrait_url(self):
        """
        获取头像图片在页面的url
        :return:
        """
        # 头像未上传则使用默认头像
        if not self.portrait:
            return settings.STATIC_URL + PORTRAIT_DEFAULT_PATH
        return self.portrait.url


class LoginUserDetail(models.Model):
    age = models.IntegerField(default=0)
    birthday = models.DateField(default=timezone.now)
    height = models.IntegerField(default=0)
    weight = models.IntegerField(default=0)
    login_user = models.OneToOneField(LoginUser, on_delete=models.CASCADE)


class LoginUserMessage(models.Model):
    user_id = models.IntegerField()

    class Meta:
        # 设置本model为抽象类，仅能被其他model继承。本model不会生成数据库表
        abstract = True
        ordering = ['user_id']


class LoginUserMessageDetail(LoginUserMessage):
    user_id = models.CharField(max_length=50)
    message_content = models.CharField(max_length=500)


class LoginUserMessageReceiveLog(LoginUserMessage):
    receive_count = models.IntegerField()


class UserMessageNew(LoginUserMessage):
    message_id = models.IntegerField()

    class Meta:
        abstract = True


class UserMessageNewDetail(UserMessageNew):
    pass


class UserImages(models.Model):
    user_id = models.IntegerField()

    class Meta:
        db_table = "xxx_useri333mages"


class UserHeads(models.Model):
    head_path = models.CharField(max_length=200)

    class Meta:
        db_tablespace = 'fish'


class Foo(models.Model):
    pass


class Bar(models.Model):
    foo = models.ForeignKey(Foo, on_delete=models.CASCADE)
    pub_date = models.DateTimeField(default=timezone.now)
    price = models.DecimalField(default=0, max_digits=5, decimal_places=2)
    description = models.CharField(max_length=500, default='')

    class Meta:
        default_related_name = 'bars'
        ordering = ['-id', '-pub_date']
        indexes = [
            models.Index(fields=['price', 'pub_date'], name='pric_pub_date_idx')
        ]


class Human(models.Model):
    name = models.CharField(max_length=50)


class Man(Human):
    height = models.IntegerField(default=0)


class Women(Human):
    weight = models.IntegerField(default=0)


class UserDetail(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    portrait = models.ImageField(upload_to=user_portrait_upload_to, default="")

    def get_portrait_url(self):
        if not self.portrait:
            return settings.PORTRAIT_DEFAULT_URL
        # 为settings.py中配置的MEDIA_URL与当前字段的值的组合
        return self.portrait.url
